package net.rock.eshop.controller.manage;

import net.rock.eshop.entity.SalesDay;
import net.rock.eshop.exception.ServerIOException;
import net.rock.eshop.exception.UnauthorizedOperationException;
import net.rock.eshop.service.PerformanceService;
import net.rock.eshop.utils.AdminChecker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.Resource;
import org.springframework.http.ContentDisposition;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

@RestController
@RequestMapping("/api/manage/performance")
public class PerformanceController {
    @Autowired
    private PerformanceService performanceService;
    @Autowired
    private AdminChecker adminChecker;

    @GetMapping("/getVols")
    public ResponseEntity<Resource> getVols(@CookieValue(value = "sessionID", defaultValue = "") String sessionId) {
        if (!adminChecker.checkAdmin(sessionId)) {
            throw new UnauthorizedOperationException();
        }

        try {
            byte[] bytes = performanceService.exportXlsx();
            String fileName = URLEncoder.encode("销量统计.xlsx", "UTF-8");
            String contentDisposition = ContentDisposition
                    .builder("attachment")
                    .filename(fileName)
                    .build().toString();
            return ResponseEntity.ok()
                    .header(HttpHeaders.CONTENT_DISPOSITION, contentDisposition)
                    .contentType(new MediaType("application", "vnd.ms-excel"))
                    .contentLength(bytes.length)
                    .body(new ByteArrayResource(bytes));
        } catch (IOException e) {
            throw new ServerIOException(e);
        }
    }

    @GetMapping("/getDaily")
    public List<SalesDay> getDaily(@CookieValue(value = "sessionID", defaultValue = "") String sessionId) {
        if (!adminChecker.checkAdmin(sessionId)) {
            throw new UnauthorizedOperationException();
        }

        return performanceService.fetchSalesDay();
    }

}
